package com.ling.pl.security.controller;

import com.ling.pl.core.commons.support.DaoPage;
import com.ling.pl.core.commons.utils.PageUtils;
import com.ling.pl.security.model.DefaultUrl;
import com.ling.pl.security.model.DefaultUser;
import com.ling.pl.security.model.RoleMember;
import com.ling.pl.security.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author bo.wang
 */
@RequestMapping("/defaultRole")
@Api(value = "defaultRole", description = "API")
@RestController("defaultRoleController")
public class DefaultRoleController extends BaseDefaultRoleController {

    Log log = LogFactory.getLog(DefaultRoleController.class);

    @Resource
    DefaultRoleService roleService;
    @Resource
    DefaultUrlService urlService;
    @Resource
    private DefaultOrgService orgService;
    @Resource
    private DefaultPositionService positionService;
    @Resource
    private DefaultUserService userService;

    @ApiOperation(value = "刷新UrlSecurity缓存")
    @RequestMapping(value = "/refreshUrlSecurityMetadata", method = RequestMethod.GET)
    public void refreshUrlSecurityMetadata() {
//        SecurityUtils.refreshUrlSecurityMetadata();
    }

    @ApiOperation(value = "刷新AllSecurity缓存")
    @RequestMapping(value = "/refreshAllSecurityMetadata", method = RequestMethod.GET)
    public void refreshAllSecurityMetadata() {
//        SecurityUtils.refreshUrlSecurityMetadata();
//        SecurityUtils.refreshComponentSecurityMetadata();
    }

    @ApiOperation(value = "刷新ComponentSecurity缓存")
    @RequestMapping(value = "/refreshComponentSecurityMetadata", method = RequestMethod.GET)
    public void refreshComponentSecurityMetadata() {
//        SecurityUtils.refreshComponentSecurityMetadata();
    }

    @ApiOperation(value = "loadUrls")
    @RequestMapping(value = "/loadUrls", method = RequestMethod.GET)
    public List<DefaultUrl> loadUrls(@ApiParam(value = "parentId") @PathVariable(name = "parentId") String parentId, @ApiParam(value = "roleId") @PathVariable(name = "roleId") String roleId) throws Exception {
        List<DefaultUrl> urls = this.urlService.loadUrlsByParentId(parentId);
        List<DefaultUrl> allUrls = urlService.loadUrlsByRoleId(roleId);
        for (DefaultUrl url : urls) {
            for (DefaultUrl roleUrl : allUrls) {
                if (url.getId().equals(roleUrl.getId())) {
                    url.setUse(true);
                    break;
                }
            }
        }
        return urls;
    }

    @ApiOperation(value = "saveRoleUrls")
    @RequestMapping(value = "/saveRoleUrls", method = RequestMethod.PUT)
    public void saveRoleUrls(@ApiParam(value = "parentId") @RequestParam("roleId") String roleId, @RequestParam("ids") Collection<String> ids) throws Exception {
        urlService.saveRoleUrls(roleId, ids);
    }

    @ApiOperation(value = "loadMembers")
    @RequestMapping(value = "/loadMembers", method = RequestMethod.GET)
    public void loadMembers(Map<String, Object> parameter) throws Exception {
        String type = (String) parameter.get("type");
        String roleId = (String) parameter.get("roleId");
        DaoPage daoPage = roleService.loadRoleMemberByRoleIdAndType(roleId, type, PageUtils.getPageIndex(parameter), PageUtils.getPageSize(parameter));
        for (Object entity : daoPage.getResult()) {
            RoleMember member = (RoleMember) entity;
            if (StringUtils.isNotEmpty(member.getUsername())) {
                member.setUser((DefaultUser) userService.loadUserByUsername(member.getUsername()));
            }
            if (StringUtils.isNotEmpty(member.getOrgId())) {
                member.setOrg(orgService.loadOrgById(member.getOrgId()));
            }
            if (StringUtils.isNotEmpty(member.getPositionId())) {
                member.setPosition(positionService.loadPositionById(member.getPositionId()));
            }
        }
    }

    @ApiOperation(value = "changeGranted")
    @RequestMapping(value = "/changeGranted", method = RequestMethod.POST)
    public void changeGranted(Collection<Map<String, Object>> members) throws Exception {
        for (Map<String, Object> map : members) {
            RoleMember rm = (RoleMember) roleService.findById(RoleMember.class, (String) map.get("memberId"));
            rm.setGranted((Boolean) map.get("granted"));
            roleService.update(rm);
        }
    }

    @ApiOperation(value = "deleteRoleMember")
    @RequestMapping(value = "/deleteRoleMember", method = RequestMethod.DELETE)
    public void deleteRoleMember(@ApiParam(value = "memberId") @PathVariable String memberId) throws Exception {
        RoleMember rm = new RoleMember();
        rm.setId(memberId);
        roleService.remove(rm);
    }

    @ApiOperation(value = "insertRoleMember")
    @RequestMapping(value = "/insertRoleMember", method = RequestMethod.PUT)
    public String insertRoleMember(@ApiParam(value = "ids") @RequestParam("ids") Collection<String> ids, @ApiParam(value = "type") @RequestParam("type") String type, @ApiParam(value = "roleId") @RequestParam("roleId") String roleId) throws Exception {
        String error = null;
        List<RoleMember> members = new ArrayList<RoleMember>();
        for (String id : ids) {
            RoleMember roleMember = new RoleMember();
            roleMember.setId(UUID.randomUUID().toString());
            roleMember.setRoleId(roleId);
            roleMember.setGranted(true);
            roleMember.setCreateDate(new Date());
            int count = 0;
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("roleId", roleId);
            if (type.equals("user")) {
                roleMember.setUsername(id);
            } else if (type.equals("org")) {
                roleMember.setOrgId(id);
            } else if (type.equals("position")) {
                roleMember.setPositionId(id);
            } else if (type.equals("group")) {
                roleMember.setGroupId(id);
            }
            count = roleService.loadRoleMemberSizeByRoleIdAndType(roleId, type, id);
            if (count > 0) {
                error = id;
                break;
            } else {
                members.add(roleMember);
            }
        }
        if (error == null) {
            for (RoleMember roleMember : members) {
                roleService.save(roleMember);
            }
        }
        return error;
    }
}

